// const { response } = require('../../utils/response');
const order = require('../../models/good/order');
class OrderService {
    static async getOrderList({ pageNum = 1, pageSize = 10 }, data) {
        try {
            // 确保分页参数是数字类型
            const pageNumInt = parseInt(pageNum) || 1;
            const pageSizeInt = parseInt(pageSize) || 10;
            
            const query = {
                ...(data?.status && { status: data.status }), // 订单状态
                ...(data?.createTime && { createTime: { $gte: new Date(data.createTime) } }), // 创建时间
                ...(data?.userId && { userId: data.userId }), // 用户ID
            };
            
            const skip = (pageNumInt - 1) * pageSizeInt;
            const limit = pageSizeInt;
            
            const total = await order.countDocuments(query);
            const orderList = await order.find(query).skip(skip).limit(limit).populate({
                path: "goodsInfo.goodId",
                populate: [
                    { path: "categoryId" },
                    { path: "tagId" }
                ]
            })
                .populate("couponId")
                .populate("userId", "-password")
                .populate("addressId")
                .lean();
                
            return {
                total,
                page: pageNumInt,
                totalPages: Math.ceil(total / pageSizeInt),
                list: orderList
            };
        } catch (error) {
            throw new Error('获取订单列表失败: ' + error.message);
        }
    }

    static async pay(orderinfo) {
        try {
            const qs = (obj) => {
                const arr = [];
                for (const key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        arr.push(key + '=' + obj[key]);
                    }
                }
                const result = arr.join('&');
                return result;
            }
            
            const { outTradeNo, totalAmount, returnUrl, payType } = orderinfo;
            
            // 验证必要参数
            if (!outTradeNo || !totalAmount || !returnUrl || !payType) {
                throw new Error('缺少必要参数');
            }
            
            orderinfo.time = Date.now();
            
            // 生成支付链接
            // let payinfo = { outTradeNo, totalAmount, returnUrl, payType };
            let url = `${process.env.NODE_ENV === 'production' ? process.env.PRODUCTION_URL : process.env.DEVELOPMENT_URL}order/spay?${Buffer.from(qs(orderinfo)).toString('base64')}`;
            return url;
        } catch (error) {
            throw new Error('支付处理失败: ' + error.message);
        }
    }
    static async updateOrderStatusById(outTradeNo, status) {
        return await order.findByIdAndUpdate(outTradeNo, { status: status }, { new: true });
    }
    static async getOrderById(orderId) {
        return await order.findById(orderId)
            .populate({
                path: "goodsInfo.goodId",
                populate: [
                    { path: "categoryId" },
                    { path: "tagId" }
                ]
            })
            .populate("couponId")
            .populate("userId", "-password")
            .populate("addressId")
            .lean();

    }
    static async createOrder(orderData) {
        try {
            // 验证必要字段
            if (!orderData.userId || !orderData.goodsInfo || !orderData.totalPrice || !orderData.estimatedDeliveryTime) {
                throw new Error('缺少必要的订单信息');
            }
            
            // 验证商品信息
            if (!Array.isArray(orderData.goodsInfo) || orderData.goodsInfo.length === 0) {
                throw new Error('商品信息不能为空');
            }
            
            // 验证每个商品项
            for (const item of orderData.goodsInfo) {
                if (!item.goodId || !item.quantity || !item.sid) {
                    throw new Error('商品信息不完整');
                }
            }
            
            return await order.create(orderData);
        } catch (error) {
            throw new Error(`创建订单失败: ${error.message}`);
        }
    }
    static async updateOrder(orderId, orderData) {
        return await order.findByIdAndUpdate(orderId, { $set: orderData }, { new: true });
    }
    static async deleteOrder(orderId) {
        return await order.findByIdAndDelete(orderId);
    }
} module.exports = OrderService;
// Compare this snippet from services/good/orderService.js: